//
//  FoodViewController.m
//  MMLOOK
//
//  Created by dllo on 15/8/27.
//  Copyright (c) 2015年 武俊娥. All rights reserved.
//

#import "FoodViewController.h"
#import "AsynConnect.h"
#import "HomeCollectionViewCell.h"
#import "FoodDetailViewController.h"
#import "SaveTools.h"
#import "MBProgressHUD.h"
#import "JudgeConnection.h"
#import "Alert.h"

@interface FoodViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain)NSMutableArray *foodArray;
@property (nonatomic, retain)UICollectionView *collection;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, retain) MBProgressHUD *mbProView;

@end

@implementation FoodViewController
//http://rm.app.hongniujia.com/json_rm.php?action=list&ver=10&page=0&category=hunlian&category2=%2F%E7%BE%8E%E9%A3%9F&pageSize=24&appCookie=channel_AppStore%20version_6.11%20oid_F5E567E6-0781-42CA-8941-CACC54D5703D%20package_com.aslibra.wt.hunlian%20platform_iphone%20ver_8.4.1%20jb_0%20t1_1440685537%20md5_1d%20t_1440072026&width=320&keyword= HTTP/1.1

- (void)dealloc
{
    [_mbProView release];
    [_url release];
    [_foodArray release];
    [_collection release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.url = @"http://api.liwushuo.com/v1/channels/118/items?limit=20&offset=0";
        self.foodArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"享美食";
    [self creatCollection];
    [self readLocalData];
    [self Connection];
    self.view.backgroundColor = [UIColor whiteColor];
}


- (void)creatCollection
{
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    layout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.width * 328 / 720);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumInteritemSpacing = 15 * OffHeight;
    layout.sectionInset = UIEdgeInsetsMake(15 * OffWidth, 15 * OffHeight, 15 * OffWidth, 15 * OffHeight);
    
    self.collection = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 104) collectionViewLayout:layout] autorelease];
    [_collection registerClass:[HomeCollectionViewCell class] forCellWithReuseIdentifier:@"food"];
    _collection.dataSource = self;
    _collection.delegate = self;
    _collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collection];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_foodArray.count == 0) {
        return 0;
    }
    return _foodArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"food" forIndexPath:indexPath];
    
    NSMutableDictionary *dic = [_foodArray objectAtIndex:indexPath.row];
    
    [cell sendDic:dic];
    
    return cell;
}

- (void)Connection
{
    [self createMbProView];
    
    [AsynConnect  asynConnectWithUrlstr:_url parmater:nil block:^(NSData *data) {
        
        if (data) {
            
            BOOL saveResult = [SaveTools saveDataWithName:[_url hash] directory:NSLibraryDirectory data:data];// 有网络时 数据储存在本地
            NSLog(@"享美食存储: %d", saveResult);
            
            [self.foodArray removeAllObjects];
            
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSMutableDictionary *littleDic = [dic objectForKey:@"data"];
            
            NSMutableArray *arr = [littleDic objectForKey:@"items"];
            [self.foodArray addObjectsFromArray:arr];
            
            [_collection reloadData];
            [_mbProView hide:YES];
        }
    }];
}

- (void)readLocalData
{
    NSData *data = [SaveTools readDataWithName:[_url hash] directory:NSLibraryDirectory];
    if (data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *littleDic = [dic objectForKey:@"data"];
        NSMutableArray *arr = [littleDic objectForKey:@"items"];
        [_foodArray addObjectsFromArray:arr];
        
        [_collection reloadData];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([JudgeConnection judgeConnection]) {
        
        FoodDetailViewController *foodDetail = [[[FoodDetailViewController alloc] init] autorelease];
        foodDetail.foodDetaildic = [_foodArray objectAtIndex:indexPath.item];
        [self.navigationController pushViewController:foodDetail animated:YES];
    } else {
        
        Alert *alert = [[Alert alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height * 3 / 4, 250, 50) LabelText:@"当前无网络连接，请检查网络状态"];
        [self.view addSubview:alert];
        [alert release];
    }
}

- (void)createMbProView
{
    self.mbProView = [[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    _mbProView.mode = MBProgressHUDModeIndeterminate;// 样式 菊花
    _mbProView.labelText = @"加载中. . .";
    [_mbProView show:YES];
    [self.view addSubview:_mbProView];
    [_mbProView hide:YES afterDelay:20];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
